<template>
  <el-dialog
    :title="isEdit ? '编辑帖子' : '发布帖子'"
    v-model="dialogVisible"
    width="70%"
    :before-close="handleClose"
  >
    <el-form :model="form" ref="formRef" :rules="rules" label-width="100px">
      <el-form-item label="分类" prop="labelId" class="form-item">
        <el-select v-model="form.labelId" placeholder="请选择分类">
          <el-option
            v-for="label in labelOptions"
            :key="label.id"
            :label="label.labelName"
            :value="label.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="标题" prop="title">
        <el-input v-model="form.title" placeholder="请输入标题"></el-input>
      </el-form-item>

      <el-form-item label="匿名发布" prop="isAnonymous">
        <el-radio-group v-model="form.isAnonymous">
          <el-radio :label="1">匿名</el-radio>
          <el-radio :label="0">不匿名</el-radio>
        </el-radio-group>
      </el-form-item>
      
      <el-form-item label="内容" prop="content">
        <RichTextEditor 
          v-model="form.content"
          :on-image-upload="handleMediaUpload"
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch } from 'vue'
import RichTextEditor from './RichTextEditor.vue'
import axios from '../plugins/axios'
import { ElMessage } from 'element-plus'

const props = defineProps({
  visible: Boolean,
  editData: Object,
  isEdit: Boolean,
  labelOptions: Array
})

const emit = defineEmits(['update:visible', 'onSubmit'])

const dialogVisible = ref(false)
const formRef = ref(null)

// 表单数据
const form = ref({
  labelId: '',
  title: '',
  content: '',
  isAnonymous: 0  // 默认不匿名
})

// 表单验证规则
const rules = {
  labelId: [{ required: true, message: '请选择分类', trigger: 'change' }],
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  content: [{ required: true, message: '请输入内容', trigger: 'blur' }]
}

// 监听编辑数据变化
watch(
  () => props.editData,
  (newVal) => {
    if (newVal && Object.keys(newVal).length > 0) {
      // 编辑模式
      form.value = {
        id: newVal.id,
        labelId: newVal.labelId,
        title: newVal.title,
        content: newVal.content,
        isAnonymous: newVal.isAnonymous
      }
    } else {
      // 新建模式
      form.value = {
        labelId: '',
        title: '',
        content: '',
        isAnonymous: 0
      }
    }
  },
  { immediate: true }
)

// 监听visible属性变化
watch(() => props.visible, (val) => {
  dialogVisible.value = val
})

// 监听dialogVisible变化
watch(dialogVisible, (val) => {
  emit('update:visible', val)
  if (!val) {
    formRef.value?.resetFields()
    form.value = {
      labelId: '',
      title: '',
      content: '',
      isAnonymous: 0
    }
  }
})

// iPhone 16 截图的标准尺寸（宽度）
const IPHONE_16_WIDTH = 1290
const IPHONE_16_HEIGHT = 2796

// 处理图片缩放
const resizeImage = (file) => {
  return new Promise((resolve) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = (e) => {
      const img = new Image()
      img.src = e.target.result
      img.onload = () => {
        const canvas = document.createElement('canvas')
        const ctx = canvas.getContext('2d')

        // 只处理大于 iPhone 16 尺寸的图片
        if (img.width > IPHONE_16_WIDTH || img.height > IPHONE_16_HEIGHT) {
          // 计算缩放比例
          let ratio = 1
          if (img.width / img.height > IPHONE_16_WIDTH / IPHONE_16_HEIGHT) {
            // 如果图片更宽，按宽度缩放
            ratio = IPHONE_16_WIDTH / img.width
          } else {
            // 如果图片更高，按高度缩放
            ratio = IPHONE_16_HEIGHT / img.height
          }

          // 设置画布尺寸
          canvas.width = img.width * ratio
          canvas.height = img.height * ratio

          // 绘制图片
          ctx.drawImage(img, 0, 0, canvas.width, canvas.height)

          // 转换为 blob
          canvas.toBlob((blob) => {
            resolve(new File([blob], file.name, { type: file.type }))
          }, file.type, 0.9)
        } else {
          // 如果图片小于标准尺寸，直接返回原图
          resolve(file)
        }
      }
    }
  })
}

// 处理图片上传
const handleImageUpload = async (file) => {
  try {
    // 处理图片尺寸
    const processedFile = await resizeImage(file)
    
    // 创建表单数据
    const formData = new FormData()
    formData.append('file', processedFile)

    // 上传图片
    const response = await axios.post('/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })

    if (response.data.code === 1) {
      return response.data.data.filePath // 返回图片URL
    } else {
      ElMessage.error('图片上传失败')
      return false
    }
  } catch (error) {
    console.error('图片上传失败:', error)
    ElMessage.error('图片上传失败')
    return false
  }
}

// 处理视频尺寸
const getVideoSize = (video) => {
  return new Promise((resolve) => {
    // 当视频元数据加载完成后获取尺寸
    video.onloadedmetadata = () => {
      resolve({
        width: video.videoWidth,
        height: video.videoHeight
      })
    }
  })
}

// 处理视频上传
const handleVideoUpload = async (file) => {
  try {
    // 创建视频元素来获取视频尺寸
    const video = document.createElement('video')
    video.src = URL.createObjectURL(file)
    const size = await getVideoSize(video)
    URL.revokeObjectURL(video.src)

    // 计算视频尺寸
    let width = size.width
    let height = size.height

    // 如果视频尺寸超过 iPhone 16 的尺寸，计算缩放比例
    if (width > IPHONE_16_WIDTH || height > IPHONE_16_HEIGHT) {
      let ratio = 1
      if (width / height > IPHONE_16_WIDTH / IPHONE_16_HEIGHT) {
        // 如果视频更宽，按宽度缩放
        ratio = IPHONE_16_WIDTH / width
        width = IPHONE_16_WIDTH
        height = height * ratio
      } else {
        // 如果视频更高，按高度缩放
        ratio = IPHONE_16_HEIGHT / height
        height = IPHONE_16_HEIGHT
        width = width * ratio
      }
    }

    // 创建表单数据
    const formData = new FormData()
    formData.append('file', file)

    // 上传视频
    const response = await axios.post('/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })

    if (response.data.code === 1) {
      // 返回视频URL和视频标签，使用计算后的尺寸
      const videoUrl = response.data.data.filePath
      return `<video 
        src="${videoUrl}" 
        controls 
        width="${width}"
        height="${height}"
        style="max-width: 100%; height: auto;"
      ></video>`
    } else {
      ElMessage.error('视频上传失败')
      return false
    }
  } catch (error) {
    console.error('视频上传失败:', error)
    ElMessage.error('视频上传失败')
    return false
  }
}

// 处理媒体上传（图片或视频）
const handleMediaUpload = async (file) => {
  const fileType = file.type.split('/')[0]
  
  if (fileType === 'image') {
    return handleImageUpload(file)
  } else if (fileType === 'video') {
    return handleVideoUpload(file)
  } else {
    ElMessage.error('不支持的文件类型')
    return false
  }
}

// 处理提交
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    const valid = await formRef.value.validate()
    if (valid) {
      const url = form.value.id ? '/post/update' : '/post/save'
      const response = await axios.post(url, form.value)
      
      if (response.data.code === 1) {
        ElMessage.success(form.value.id ? '编辑成功' : '发布成功')
        emit('onSubmit')
        dialogVisible.value = false
      } else {
        ElMessage.error(response.data.msg || '操作失败')
      }
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  }
}

// 处理关闭
const handleClose = () => {
  dialogVisible.value = false
}
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-select) {
  width: 100%;
}

/* 富文本编辑器占满整行 */
:deep(.el-form-item.form-item) {
  margin: 0;
}

:deep(.el-form-item__content video) {
  max-width: 100%;
  height: auto;
  margin: 10px 0;
  display: block;  /* 确保视频居中显示 */
  margin-left: auto;
  margin-right: auto;
}
</style> 